package com.dily.study.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dily.study.user.entity.Permission;
import com.dily.study.user.entity.Role;
import com.dily.study.user.entity.User;
import com.dily.study.user.entity.dto.LoginUser;
import com.dily.study.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Date: 2022-06-10 星期五
 * Time: 11:11
 * Author: Dily_Su
 * Remark:
 */
@Service
public class UserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        // 如果用户不存在，抛出异常
        if (Objects.isNull(user))
            throw new RuntimeException("用户不存在");

        // 查询角色信息
        List<String> roles = roleService.getRolesByUserId(user.getId()).stream().map(Role::getRoleKey).collect(Collectors.toList());
        //查询权限信息
        List<String> permissions = permissionService.getPermissionsByUserId(user.getId()).stream().map(Permission::getPerms).collect(Collectors.toList());
        // 将 user 封装为 UserDetail
        return new LoginUser(user, roles, permissions);
    }
}
